#!/bin/bash
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2022-11-10 14:19:49
# @LastEditTime: 2023-12-06 15:48:09
# @Description:
###
# curl  -s http://wuyou.run/services/python3|bash



# 判断是否为中国地区
is_china() {
    # 使用简单的方法判断，您也可以根据实际需求添加更多判断条件
    if [[ $(curl -sSL https://ipapi.co/country/) = "CN" ]]; then
        return 0
    else
        return 1
    fi
}



# 根据地区选择镜像源
select_country() {
    if is_china; then
        echo "检测在中国地区，将使用国内镜像源。"
        python_repository="https://repo.huaweicloud.com/python"
    else
        echo "检测不在中国地区，将使用官方镜像源。"
        python_repository="https://www.python.org/ftp/python"
    fi
}





# 定义要查询的网站列表
websites=(
    "https://docs.python.org/3/"
    "https://www.jetbrains.com/pycharm/"
    "https://anaconda.org/"
    "https://www.spyder-ide.org/"
    "https://flask.palletsprojects.com/"
    "https://numpy.org/"
    "https://www.scipy.org/"
)

# 初始化最新版本号变量
latest_version=""

# 循环遍历每个网站
for url in "${websites[@]}"
do

    # 使用 curl 命令获取网站内容
    response=$(curl -sL "$url")

    # 提取第一个版本号信息
    version=$(echo "$response" | grep -oP "Python [0-9]+\.[0-9]+\.[0-9]+" | head -n 1|awk '{print $2}' )
    # 如果版本号不为空，将其存储到变量中
    if [ -n "$version" ]; then
        latest_version="$version"
        echo "查询:$url  版本号: $latest_version"
        break  # 如果找到一个版本号，就停止继续查询其他网站
    fi
done




if [ -d  /usr/local/python3 ]; then
    echo "检测到python3已安装"
else
    yum install python3-devel python3-ldap openldap-devel  \
        libffi-devel    libxml2-devel libxslt-devel \
        bzip2-devel expat-devel bzip2-devel readline-devel \
        libjpeg-devel libpng-devel libtiff-devel libwebp-devel -y

    yum install openssl-devel openssl11 openssl11-devel -y
    #安装openssl11，后期的pip3安装网络相关模块需要用到ssl模块。
    export CFLAGS=$(pkg-config --cflags openssl11)
    export LDFLAGS=$(pkg-config --libs openssl11)
    
    if [ ! -f Python-3.*.xz ]; then
        # 构建 wget 命令，下载指定版本
        select_country
        echo "Python下载源: $python_repository"
        wget  -c $python_repository/$latest_version/Python-$latest_version.tar.xz
        if [ $? != 0 ]; then
            echo "下载失败 !!!"
            exit 1
        fi
    fi

    tar xf Python*xz
    cd Python-3.*
    ./configure --prefix=/usr/local/python3
    make -j 2
    make install
    # altinstall在安装时会区分已存在的版本

    rm /usr/local/bin/python3 /usr/bin/python3 /usr/local/bin/pip3 -rf
    ln -s /usr/local/python3/bin/python3 /usr/local/bin/python3
    ln -s /usr/local/python3/bin/pip3 /usr/local/bin/

fi
